package cn.lg.soar.cloud.core.config;

import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.common.util.current.CurrentUser;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.common.util.data.RandomUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * feign调用前设置客户端地址和当前用户
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class FeignSecretRequestInterceptor implements RequestInterceptor {


    private final byte[] secret;
    private final long duration;

    public FeignSecretRequestInterceptor(CloudProperties properties) {
        this.secret = properties.getSecret().getBytes();
        this.duration = properties.getExpire().toMillis();
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        if (attributes != null) {
            // 准备数据
            javax.servlet.http.HttpServletRequest request = attributes.getRequest();
            String random = RandomUtil.getString(32);
            String expire = String.valueOf(System.currentTimeMillis() + duration);
            // 数据签名
            MessageDigest digest;
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
            digest.update(secret);
            digest.update(random.getBytes());
            digest.update(expire.getBytes());
            String sign = DataUtil.byteToHex(digest.digest());
            // 设置请求头
            requestTemplate.header("User-Agent", request.getHeader("User-Agent"));
            requestTemplate.header(CurrentUser.USER_KEY, request.getHeader(CurrentUser.USER_KEY));
            requestTemplate.header(IpUtil.CLIENT_IP, IpUtil.getRemoteIp(request));
            requestTemplate.header("security-random", random);
            requestTemplate.header("security-expire", expire);
            requestTemplate.header("security-sign", sign);
        }
    }
}
